﻿namespace FsWeb.Controllers

open System.Collections.Generic
open System.Web
open System.Web.Mvc
open System.Net.Http
open System.Web.Http
open AttributeRouting;
open AttributeRouting.Web;
open AttributeRouting.Web.Http
open System.Diagnostics
open System
open FsWeb.Models
open FsWeb.Utils
open Business
open Business.BusinessDomain
//open NewBusiness;



[<RoutePrefix("/api/Url")>]
type UrlController(bc:IBusinessContext) =
 inherit ApiController()

  [<AuthorizeAttribute>]
  [<GET("GetTitle?{url}");HttpGet>]
  member this.GetTitle(url:string) = 
         let ur = bc.UrlContext.FindBy url 
         if ur = null || ur.Title |> String.IsNullOrEmpty then 
          let f = async {
            let cl =  new System.Net.WebClient()
            do cl.Headers.Add("user-agent", "TagThis.Org title bot, v0.1")
            do cl.Encoding <- System.Text.Encoding.Default
            let! str =  cl.AsyncDownloadString(new Uri(url))
            let strl = str.ToLower()
            let startTitle = strl.IndexOf("<title>")
            let startEndTitle = if startTitle = -1 then -1 else strl.IndexOf("</title>")
            return if startTitle = -1 || startEndTitle = -1 then "" else str.Substring(startTitle + "<title>".Length, startEndTitle - (startTitle + "<title>".Length))
          }
          f |> Async.Catch |> Async.RunSynchronously
          |> function 
          | Choice1Of2 r -> r
          | Choice2Of2 e -> ""
         else
            ur.Title
            
         